package cn.wolfcode.web.advice;

import cn.wolfcode.domain.Journal;
import cn.wolfcode.service.IJournalService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component //把当前类注入到spring容器中
@Aspect    //把当前类标识为一个切面供容器读取
public class AopConfig {
    @Autowired
    private HttpServletRequest request;
   @Autowired
    private IJournalService journalService;
    /**
     * 指定切入点
     * 对贴有自定义注解@RequiredPermission的方法，进行切面
     */
    @Pointcut("@annotation(cn.wolfcode.util.RequiredPermission)")
    private void useMethod() {
    }

    /**
     * 对切入点进行增强
     */
    @Around(value = "useMethod()")
    public Object recordLog(ProceedingJoinPoint jp) throws Throwable {
        Journal journal = new Journal();
        Object result=null;
        Date date = new Date();
        long start = date.getTime();
        //执行处理方法（执行控制器中的方法）
        try {
            result   = jp.proceed();
            journal.setOpresult(true);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            journal.setErrorMessage(throwable.getMessage());
        }
        //result是方法的返回值，直接return回去就会返回给springmvc处理
        /*proceedingJoinPoint.*/
        //new 一个封装日志数据的对象
        Long end= System.currentTimeMillis();
        journal.setTime(end-start);
        Signature signature = jp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        journal.setOptiome(date);
        if (method != null) {
            RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
            journal.setOperation(annotation.name());
            journal.setRequest(annotation.expression());
        }
        //获得用户IP地址


        journal.setIp(request.getRemoteAddr());
        //获得地址上的参数
        journal.setRequests(request.getQueryString());

        journal.setUsername(UserContext.getCurrentUser().getUsername());

       /* journalService.save(journal);*/
     return result;
    }


}